﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Atmk.WaterMeter.MIS.Commons.Interfaces.GateWay;
using NLog;
using WeifenLuo.WinFormsUI.Docking;

namespace Atmk.WaterMeter.MIS.LogicTestForm.Views
{
    public partial class CT_NBDeviceView : DockContent
    {
        private static readonly ILogger _Logger = LogManager.GetCurrentClassLogger();
        private readonly ICT_NBIoT_DevicesManage _ctNbioTDevicesManage;
        public CT_NBDeviceView(
            ICT_NBIoT_DevicesManage ctNbioTDevicesManage)
        {
            _ctNbioTDevicesManage = ctNbioTDevicesManage;
            InitializeComponent();
          
            BindClick();
        }

        private void BindClick()
        {
            _AddDevice.Click += (s, e) =>
            {
               AddDevice();
            };
            _DelDevice.Click += (s, e) =>
            {
                DelDevice();
            };
        }

        private void DelDevice()
        {
            try
            {
                var result = _ctNbioTDevicesManage.DeleteDevice(_DeviceId.Text);
                if (result)
                {
                    _DeviceId.Text = "";
                }
                Info($"设备Id:删除{(result?"成功":"失败")}");
            }
            catch (Exception e)
            {
                Error(e.Message);
                Error(e.StackTrace);
            }
        }

        private void AddDevice()
        {
            try
            {
                var result = _ctNbioTDevicesManage.RegisterDevice(_MeterNoText.Text);
                _DeviceId.Text = result.ToId();
                Info($"设备Id:{result.ToId()}");
            }
            catch (Exception e)
            {
                Error(e.Message);
                Error(e.StackTrace);
            }
            
        }

        private void Info(string message)
        {
            Invoke((EventHandler)delegate
            {
                _listBox.Items.Add($"{DateTime.Now:T}[Info]:{message}");
            });
        }
        private void Error(string message)
        {
            Invoke((EventHandler)delegate
            {
                _listBox.Items.Add($"{DateTime.Now:T}[Error]:{message}");
            });
        }
    }
}
